<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>秒杀系统</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-plus/2.4.4/index.css">
    <style>
        .container {
            width: 1200px;
            margin: 20px auto;
        }
        .goods-card {
            margin-bottom: 20px;
        }
        .price {
            color: #f56c6c;
            font-size: 20px;
            font-weight: bold;
        }
        .original-price {
            color: #999;
            text-decoration: line-through;
            margin-left: 10px;
        }
        .error-message {
            color: red;
            margin: 10px 0;
            display: none;
        }
        .success-message {
            color: green;
            margin: 10px 0;
            display: none;
        }
        .message-box {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            padding: 15px;
            border-radius: 4px;
            min-width: 200px;
            text-align: center;
            box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
        }
        .success {
            background-color: #67C23A;
            color: white;
        }
        .error {
            background-color: #F56C6C;
            color: white;
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <el-row :gutter="20">
            <el-col :span="8" v-for="goods in goodsList" :key="goods.id">
                <el-card class="goods-card">
                    <h3>{{ goods.goodsName }}</h3>
                    <p>{{ goods.goodsDesc }}</p>
                    <div>
                        <span class="price">￥{{ goods.price }}</span>
                        <span class="original-price">￥{{ goods.originalPrice }}</span>
                    </div>
                    <p>库存: {{ goods.stock }}</p>
                    <p>开始时间: {{ formatTime(goods.startTime) }}</p>
                    <p>结束时间: {{ formatTime(goods.endTime) }}</p>
                    <el-button type="danger" 
                             @click="seckill(goods.id)"
                             :disabled="!canSeckill(goods)">
                        {{ getSeckillButtonText(goods) }}
                    </el-button>
                </el-card>
            </el-col>
        </el-row>

        <transition name="el-fade-in-linear">
            <div class="message-box" :class="messageType" v-if="showMessage">
                {{ message }}
            </div>
        </transition>

        <el-dialog v-model="dialogVisible" title="提示" width="30%">
            <span>{{ dialogMessage }}</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <script src="https://cdn.staticfile.org/vue/3.4.3/vue.global.min.js"></script>
    <script src="https://cdn.staticfile.org/element-plus/2.4.4/index.full.min.js"></script>
    <script src="https://cdn.staticfile.org/axios/1.6.2/axios.min.js"></script>
    <script>
        const { createApp, ref } = Vue;

        const app = createApp({
            setup() {
                const goodsList = ref([]);
                const dialogVisible = ref(false);
                const dialogMessage = ref('');
                const message = ref('');
                const messageType = ref('');
                const showMessage = ref(false);

                // 模拟用户ID
                const userId = 1001;

                const loadGoods = async () => {
                    try {
                        const response = await axios.get(`/api/seckill/goods?userId=${userId}`);
                        goodsList.value = response.data.data;
                    } catch (error) {
                        console.error('加载商品失败:', error);
                    }
                };

                const formatTime = (time) => {
                    return new Date(time).toLocaleString();
                };

                const canSeckill = (goods) => {
                    const now = new Date().getTime();
                    return now >= new Date(goods.startTime).getTime() 
                        && now <= new Date(goods.endTime).getTime()
                        && goods.stock > 0
                        && !goods.purchased;
                };

                const getSeckillButtonText = (goods) => {
                    if (goods.purchased) {
                        return '已抢购';
                    }
                    const now = new Date().getTime();
                    if (now < new Date(goods.startTime).getTime()) {
                        return '未开始';
                    }
                    if (now > new Date(goods.endTime).getTime()) {
                        return '已结束';
                    }
                    if (goods.stock <= 0) {
                        return '已售罄';
                    }
                    return '立即秒杀';
                };

                const showMessageBox = (msg, type) => {
                    console.log('显示消息:', msg, type);
                    message.value = msg;
                    messageType.value = type;
                    showMessage.value = true;

                    setTimeout(() => {
                        showMessage.value = false;
                    }, 3000);
                };

                const seckill = async (goodsId) => {
                    try {
                        const response = await axios({
                            method: 'post',
                            url: `/api/seckill/${goodsId}`,
                            params: { userId },
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        });
                        
                        const result = response.data;
                        console.log('秒杀响应:', result);
                        
                        if (result.code === 0) {
                            showMessageBox('秒杀请求已提交，正在处理...', 'success');
                            pollOrderResult(userId, goodsId);
                        } else {
                            showMessageBox(result.msg, 'error');
                            loadGoods();
                        }
                    } catch (error) {
                        console.error('秒杀请求失败:', error);
                        showMessageBox('系统错误，请稍后重试', 'error');
                    }
                };

                const pollOrderResult = async (userId, goodsId) => {
                    const maxAttempts = 10;
                    let attempts = 0;
                    
                    const poll = async () => {
                        if (attempts >= maxAttempts) {
                            showMessageBox('订单创建超时，请稍后查看订单列表', 'error');
                            loadGoods();
                            return;
                        }
                        
                        try {
                            const response = await axios.get(`/api/seckill/order/result?userId=${userId}&goodsId=${goodsId}`);
                            const result = response.data;
                            
                            if (result.code === 0) {
                                if (result.data) {
                                    const orderId = result.data;
                                    showMessageBox('秒杀成功！正在跳转...', 'success');
                                    // 延迟一秒跳转，让用户看到成功提示
                                    setTimeout(() => {
                                        window.location.href = `/order.html?orderId=${orderId}`;
                                    }, 1000);
                                    return;
                                }
                                // 继续轮询
                                attempts++;
                                setTimeout(poll, 1000);
                            } else {
                                showMessageBox(result.msg, 'error');
                                loadGoods();
                            }
                        } catch (error) {
                            attempts++;
                            showMessageBox('查询订单失败，请稍后查看订单列表', 'error');
                            setTimeout(poll, 1000);
                        }
                    };
                    
                    poll();
                };

                // 页面加载时获取商品列表
                loadGoods();

                return {
                    goodsList,
                    dialogVisible,
                    dialogMessage,
                    message,
                    messageType,
                    showMessage,
                    formatTime,
                    canSeckill,
                    getSeckillButtonText,
                    seckill,
                    showMessageBox,
                };
            }
        });

        app.use(ElementPlus);
        app.mount('#app');
    </script>
</body>
</html> 